package com.fengye.algorithms.leecode;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author fengye
 * @Date 2023/4/8 11:39
 **/
public class TwoSum167 {
    public int[] twoSum(int[] numbers, int target) {
        if(numbers.length == 2 && (numbers[0] + numbers[1]) == target) {
            return new int[]{1,2};
        }

        Map<Integer, Integer> map = new HashMap<>();
        for(int i=0,j=numbers.length - 1; i <= j ; i++,j--) {
            if(numbers[i] + numbers[j] == target) {
                return new int[] {i+1, j+1};
            }
            int temp = target -numbers[i];
            if(map.containsKey(temp)) {
                int idx = map.get(temp);
                return new int[] {Math.min(i, idx) + 1, Math.max(i, idx)+1};
            }
            temp = target - numbers[j];
            if(map.containsKey(temp)) {
                int idx = map.get(temp);
                return new int[] {Math.min(j, idx) + 1, Math.max(j, idx)+1};
            }
            map.put(numbers[i],i);
            map.put(numbers[j],j);
        }

        return null;
    }
}
